package org.jeecg.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.jeecg.modules.entity.DbFinanceManage;
import org.jeecg.modules.entity.DbRepayment;
import org.jeecg.modules.mapper.DbRepaymentMapper;
import org.jeecg.modules.service.IDbFinanceManageService;
import org.jeecg.modules.service.IDbRepaymentService;
import org.jeecg.modules.service.IDbYearlyPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @Description: db_repayment
 * @Author: jeecg-boot
 * @Date: 2024-06-13
 * @Version: V1.0
 */
@Service
public class DbRepaymentServiceImpl extends ServiceImpl<DbRepaymentMapper, DbRepayment> implements IDbRepaymentService {


    @Autowired
    private IDbFinanceManageService dbFinanceManageService;
    @Autowired
    private IDbYearlyPlanService dbYearlyPlanService;

    @Override
    @Transactional
    public void add(DbRepayment dbRepayment) {
        this.save(dbRepayment);
//        QueryWrapper<DbRepayment> qw = new QueryWrapper<>();
        this.extracted(dbRepayment);
    }



    @Override
    @Transactional
    public void delete(String id) {
        DbRepayment dbRepayment = this.getById(id);
        this.removeById(id);
        this.extracted(dbRepayment);
    }

    // 获取回款总额修改财务表记录
    private void extracted(DbRepayment dbRepayment) {
        // 获取现有回款总额
        QueryWrapper<DbRepayment> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("IFNULL(sum(amount),0) as totalAmount")
                .eq("contract_id", dbRepayment.getContractId())
                .eq("deleted", 0);
        Map<String, Object> map = this.getMap(queryWrapper);
        // 回款金额
        BigDecimal sumCount = (BigDecimal) map.get("totalAmount");
        // 修改财务表记录
        dbFinanceManageService.updateDbFinanceManage(dbRepayment.getContractId(), sumCount);
        // 根据年份修改年度计划回款进度
        dbYearlyPlanService.updateRepayProgress(dbRepayment.getContractId());
    }
}
